package Controller;
import Controller.SimulatorObject.SimulatorObjectType;
import gui.Form;
import connection.ControllerMessage;
import connection.Relay;
import connection.SensorMessage;
import java.util.ArrayList;



/**
 *
 * @author imahilus
 */
public class SimulatorController extends Thread
{
    private SimulatorClock timer;
    private Form           gui;
    public static volatile ArrayList<int[]> trafficLightChanges = new ArrayList<int[]>();
    public static Relay                     relay;


    
    public SimulatorController(Relay controlRelay, Form gui)
    {
        timer = new SimulatorClock();
        this.gui = gui;
        SimulatorController.relay = controlRelay;

        //test stuff
        /*
        int trafficLight = 7;
        for(int lane = 27; lane < 28; lane += 1)
        {
            for(int i = 0; i < 1; i++) { this.AddObject(SimulatorObjectType.car, lane); }
            this.SetTrafficLight(lane, 1);
        }
        //*/

        this.start();
    }



    @Override
    public void run()
    {
        ControllerMessage control;
        SensorMessage  sensor;
        while(true)
        {
            control = SimulatorController.relay.getControllerMessage();
            if(control != null)
            {
                this.SetTrafficLight(control.getLane(), control.getLightState());
            }

            sensor  = SimulatorController.relay.getSensorMessage();
            if(sensor != null)
            {
                this.AddObject(SimulatorObjectType.motorised, sensor.getLane());
            }
        }
    }



    public void AddObject(SimulatorObject.SimulatorObjectType type, int lane)
    {
        if((lane >= 0)&&(lane < 28))
        {
            SimulatorWaypoints.lanes[lane].contents.add(new SimulatorObject(lane, type));
        }
    }



    /**
     * Set the traffic to its green state (let the people move), or red state (people won't pass).
     * Consider orange the same as red, since people aren't allowed to pass.
     * @param lane the number of the lane whose traffic light to set
     * @param colour the colour of the light, 0 = red, 1 = green, 2 = orange
     */
    public void SetTrafficLight(int lane, int colour)
    {
        SimulatorController.trafficLightChanges.add(new int[]{lane, colour});
    }
}
